// pages/shop/deal/deal.js
var UTILS = require("../../../utils/util.js");
var API = require("../../../config/api.js");

var APP = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    RESOURCE_ROOT: "",
    shopId: -1,
    dealTotalPrice: 0,
    note: "",
    cartList: []
  },
  /**
   * 自定义函数
   */
  onNoteChanged: function (event) {
    this.setData({
      note: event.detail
    });
  },
  onClickLeft: function () {
    wx.navigateBack({
      delta: 1, // 回退前 delta(默认为1) 页面
      success: function(res){}
    });
  },
  getCartList: function (userId, shopId, callback) {
    var _this = this;
    var url = API.GET_PRODUCT_CHECKED_LIST_IN_CART + "/" + userId + "/" + shopId;
    var header = {
      Authorization: APP.globalData.token,
      userId: APP.globalData.userInfo.id
    };
    UTILS.httpGet(url, header, function(data) {
      callback(data.result);
    });
  },
  doDeal: function () {
    var _this = this;
    var url = API.CREATE_ORDER;
    var header = {
      Authorization: APP.globalData.token,
      userId: APP.globalData.userInfo.id
    };
    var requestParam = {
      userId: APP.globalData.userInfo.id,
      shopId: this.data.shopId,
      note: this.data.note,
    };

    UTILS.httpPost(url, header, requestParam, function(data) {
      UTILS.showSuccessToast("下单成功", function () {
        _this.setData({
          note: "",
          shopId: -1
        })
        setTimeout(function() {
          wx.navigateTo({
            url: '../../ucenter/order/detail/detail?orderId=' + data.result.id,
            success: function(res){},
            fail: function() {},
            complete: function() {}
          });
        }, 500);
        
      });
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(options);
    this.setData({
      shopId: options.shopId
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.setData({
      RESOURCE_ROOT: API.RESOURCE_ROOT
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var _this = this;
    var userId = APP.globalData.userInfo.id;
    var shopId = this.data.shopId;
    this.getCartList(userId, shopId, function(data) {
      var totalPrice = 0;
      for (let cart of data) {
        totalPrice += cart.productPrice * cart.productCount;
      }
      _this.setData({
        cartList: data,
        dealTotalPrice: totalPrice * 100
      });
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})